package rx.genarator.comprehension.parser;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import org.xml.sax.EntityResolver;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

import rx.genarator.HibernateDTDEntityResolver;

public class XMLUtils {

	public static Document readHibernateXML(File xmlFile) throws DocumentException, IOException{
		SAXReader reader = new SAXReader();
		reader.setValidation(false);
		//reader.setEntityResolver(null);
		//reader.setIncludeExternalDTDDeclarations(false);
		reader.setStripWhitespaceText(false);
		reader.setMergeAdjacentText(false);
		reader.setEntityResolver(new HibernateDTDEntityResolver());
		reader.setErrorHandler( new ErrorHandler(){

			public void error(SAXParseException e) throws SAXException {
				e.printStackTrace();					
			}

			public void fatalError(SAXParseException e) throws SAXException {
				e.printStackTrace();
			}

			public void warning(SAXParseException e) throws SAXException {
				e.printStackTrace();
			}
				
		} );
		FileInputStream fis=new FileInputStream(xmlFile);
		Document doc=reader.read(fis);
		fis.close();
		return doc;
	}
	
	public static Document readNoDTDXML(InputStream xmlInputStream) throws DocumentException, IOException{
		SAXReader reader = new SAXReader();
		reader.setValidation(false);
		//reader.setEntityResolver(null);
		//reader.setIncludeExternalDTDDeclarations(false);
		reader.setStripWhitespaceText(false);
		reader.setMergeAdjacentText(false);
		reader.setEntityResolver(new EntityResolver(){
			public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {				
				return null;
			}
		});
		reader.setErrorHandler( new ErrorHandler(){

			public void error(SAXParseException e) throws SAXException {
				e.printStackTrace();					
			}

			public void fatalError(SAXParseException e) throws SAXException {
				e.printStackTrace();
			}

			public void warning(SAXParseException e) throws SAXException {
				e.printStackTrace();
			}
				
		} );
		Document doc=reader.read(xmlInputStream);
		xmlInputStream.close();
		return doc;
	}
	
	public static String getValue(Node parentNode,String xpath){
		Node node = parentNode.selectSingleNode(xpath);
		if(node == null) return null;
		return node.getText();
	}
}
